package com.ng8866.gateway.config;

import com.ng8866.gateway.filter.CustomerCenterFilter;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "")
@Data
@Slf4j
public class RoutesConfig {
    private List<Routes> routes = new ArrayList<>();

    @Bean
    public RouteLocator apiLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routesBuilder = builder.routes();
        for (Routes route : routes) {
            if (route.getEnabled()) {
                log.info("添加路由：{}", route);
                addRoutesForService(routesBuilder, route.getUri(), route.getPaths());
            } else {
                log.warn("忽略路由：{}", route.getUri());
            }
        }
        // 添加客服中心单点登陆路由，需要时取消注释即可
//        routesBuilder.route(r -> r.path(GatewayConfig.getPrefixedPath("/customer/sub/**"))
//                .filters(f -> f.filter(new CustomerCenterFilter())
//                        .stripPrefix(2)
//                )
//                .uri("lb://admin-service")
//        );
        return routesBuilder.build();
    }

    /**
     * 添加一组路由。
     *
     * @param routes      路由构建器的构建器
     * @param targetUri   路由的目标URI
     * @param apiPatterns 路由匹配的路径模式数组
     */
    private void addRoutesForService(RouteLocatorBuilder.Builder routes, String targetUri, String... apiPatterns) {
        for (String apiPattern : apiPatterns) {
            routes.route(r -> r.path(GatewayConfig.getPrefixedPath(apiPattern))
                    .filters(f -> f.stripPrefix(2))
                    .uri(targetUri));
        }
    }

    @Data
    @ToString
    public static class Routes {
        private Boolean enabled;
        private String uri;
        private String[] paths;
    }
}